import {EventEmitter, Injectable} from '@angular/core';
import {Product} from "../entity/product";
import {Comment} from "../entity/comment";
import {Observable} from "rxjs";
import {HttpClient, HttpHeaders, HttpParams} from "@angular/common/http";

const httpOptions = {
  headers: new HttpHeaders({
    'Content-Type':  'application/json',
    'Authorization': 'my-auth-token'
  })
};

@Injectable({
  providedIn: 'root'
})
export class ProductService {

  searchEvent: EventEmitter<ProductServiceParams> = new EventEmitter();

  constructor(private httpClient: HttpClient) {
  }

  getProducts(): Observable<Product[]> {
    return this.httpClient.get<Product[]>('/api/products');
  }

  getProduct(id: number): Observable<Product> {
    return this.httpClient.get<Product>('/api/product/' + id);
  }

  getCommentForProductId(id: number): Observable<Comment []> {
    /*把符合条件的id加入到返回的数据内容中*/
    return this.httpClient.get<Comment[]>(`/api/product/${id}/comments`);
  }

  getSearchProducts(params: ProductServiceParams): Observable<Product[]> {
    console.log("我来了")
  /*  return this.httpClient.get<Product[]>("/api/product/search", {params: this.getParams(params)});*/
    return this.httpClient.post<Product[]>("/api/product/search",params ,httpOptions);
  }

  getAllCategories(): string[] {
    return ['硬件设备', '电子产品', '图书'];
  }

  getParams(params: ProductServiceParams): HttpParams {
    /*let param: HttpParams;*/
    return Object.keys(params)
      .filter(key => params[key])
      .reduce((param: HttpParams, key: string) => {
        param.append(key, params[key]);
        return param;
      }, new HttpParams());
  }

}

export class ProductServiceParams {

  constructor(
    public titile?: string,
    public price?: string,
    public category?: string
  ) {
  }
}
